'use strict'


const http = require('http')



/**
 * .jpg .jpeg   ->image.jpeg
 * 
 * .png   ->image/png
 * 
 * .gif  -> image/gif
 * 
 * .ico   ->image/x-icon
 * 
 * .txt   ->text/plain
 * 
 * .json   -> text/json   或   application/json
 * 
 * .xml   ->textxml   或 aplication/xml
 */





let html = `
        <!DOCTYPE html>
        <html>
            <head>
                <title>first HTTP </title>
            </head>
            <body>
                你好.
            </body>
        </html>
    `;

let routerTable = {
    '/':async(req,res)=>{
        res.setHeader('content-type',
            'text/plain;charset=utf-8')
        console.log(res.data)
        res.end(html);
    },
    '/test':async(req,res)=>{
        let status = parseInt(Math.random() * 200)+199
        res.statusCode = status
        res.end('test end')
    },
    '/data':async(req,res)=>{
        let bufferList = []
        let bufferLength = 0

        
        req.on('data',chunk=>{
            bufferLength += chunk.length
            bufferList.push(chunk)
        })
        let bodyData = null;
        req.on('end',()=>{
            if(bufferList.length > 0){
                bodyData = Buffer.concat(bufferList,bufferLength);
                bufferList = [];
            }
            if(bodyData){
                res.end(bodyData);
            }else{
                res.end()
            }
        })
    }
}
http.createServer((req,res)=>{

    if(!routerTable[req.url]){
        res.statusCode = 404
        res.end('page not found')
        return
    }
    routerTable[req.url](req,res)
    // console.log(req);
    
    // res.setHeader('content-type',
    //     'text/plain;charset=utf-8')   //输出html文本

    
}).listen(3456)